package com.somlsis.activity

import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode
import com.amap.api.location.AMapLocationListener
import com.base.BaseActivity
import com.base.DeviceCenter
import com.base.DeviceConfig
import com.event.StoreEvent
import com.net.HttpResponse
import com.somlsis.R
import com.somlsis.bean.Motion
import com.somlsis.bean.MotionData
import com.somlsis.bean.UserLatLng
import com.somlsis.databinding.ActivityRunningBinding
import com.utils.ByteUtils
import com.utils.GsonUtil
import com.utils.StringUtils
import com.widget.LongClickCircleView.OnLongClickCircleViewListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


class RunningActivity : BaseActivity<ActivityRunningBinding>(), AMapLocationListener {

    //声明mlocationClient对象
    private lateinit var mlocationClient: AMapLocationClient

    //声明mLocationOption对象
    private lateinit var mLocationOption: AMapLocationClientOption
    override fun getViewBinding(): ActivityRunningBinding {
        return ActivityRunningBinding.inflate(LayoutInflater.from(this))
    }

    override fun onResume() {
        super.onResume()
        createView()
    }

    override fun createView() {
        createLocation()
        deviceCenter.setOnStrideListener(object : DeviceCenter.OnStrideListener {
            override fun onStride(
                isRun: Boolean,
                speed: String,
                frequency: Float,
                stride: Float,
                distance: Float,
                motionTime: Long,
                motionList: ArrayList<Motion>
            ) {
                binding.stepSize.text = stride.toString()
                binding.strideFrequency.text = frequency.toString()
                binding.speedAllocation.text = speed
                binding.distance.text = distance.toString()
                binding.exerciseTime.text = StringUtils.convertMillisToHMS(motionTime)
            }
        })
        binding.lock.setOnClickListener {
            test()
        }
        binding.stopBt.setOnLongClickCircleViewListener(object : OnLongClickCircleViewListener {
            override fun onLongClickFinish() {
                val motionList = deviceCenter.stopRunning()
                val latLngs = deviceCenter.getLatLngs()
                val toJson = GsonUtil.toJson(MotionData(motionList, latLngs))
                toJson?.let {
                    dataCenter.store(toJson, object : Callback<HttpResponse<String>> {
                        override fun onResponse(
                            call: Call<HttpResponse<String>>,
                            response: Response<HttpResponse<String>>
                        ) {
                            EventBus.getDefault().post(StoreEvent())
                            finish()
                        }

                        override fun onFailure(call: Call<HttpResponse<String>>, t: Throwable) {

                        }

                    })
                }

            }

        })
        binding.continueBt.setOnLongClickCircleViewListener(object : OnLongClickCircleViewListener {
            override fun onLongClickFinish() {
                deviceCenter.pauseRunning()
                refreshUI()
            }

        })
        binding.mapBt.setOnClickListener(object : OnClickListener {
            override fun onClick(v: View?) {
                startActivity(Intent(this@RunningActivity, RunningMapActivity::class.java))
            }

        })

    }

    private fun createLocation() {
        mlocationClient = AMapLocationClient(this)
        //初始化定位参数
        mLocationOption = AMapLocationClientOption()
        //设置定位监听
        mlocationClient.setLocationListener(this)
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.locationMode = AMapLocationMode.Hight_Accuracy
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.interval = 30000
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption)
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation()
    }

    private fun refreshUI() {
        if (deviceCenter.getMotionState() == DeviceConfig.MOTION_STATE_RUNNING) {
            binding.continueBt.setSrc(R.mipmap.icon_start)
        } else {
            binding.continueBt.setSrc(R.mipmap.icon_start)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onStoreEvent(event: StoreEvent) {
        finish()
    }

    private fun test() {
        val it = byteArrayOf(7, 88, 1, 47, -33, 0, 6, 1, 0, 0)
        var isRun = ByteUtils.getByteToBoolean(it[0])

        var speed = ByteUtils.getByteToInt(it[1], it[2]) / 256f
        var frequency = ByteUtils.getByteToInt(it[3]) * 2f
        var stride = ByteUtils.getByteToInt(it[4], it[5]) / 2f
        var distance = ByteUtils.getByteToInt(it[6], it[7], it[8], it[9]) / 10000f
        Log.d("data", "isRun:$isRun")
        Log.d("data", "速度:$speed")
        Log.d("data", "步频:$frequency")
        Log.d("data", "幅度:$stride")
        Log.d("data", "总距离:$distance")

        binding.stepSize.text = stride.toString()
        binding.strideFrequency.text = frequency.toString()
        binding.speedAllocation.text = StringUtils.getPace(speed)
        binding.distance.text = distance.toString()
    }

    override fun onLocationChanged(location: AMapLocation?) {
        Log.d("LocationChange", "Location:${location.toString()}")
        location?.let {

            if (it.errorCode == 0) {
                deviceCenter.addLatLng(UserLatLng(it.latitude, it.longitude))
            } else {
                Log.e(
                    "AmapError", "location Error, ErrCode:"
                            + it.errorCode + ", errInfo:"
                            + it.errorInfo
                );
            }
        }

    }

}
